<?php


namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Validate;
use think\Session;
class Login extends Controller
{
    public function login(){
        $username = Session::get('username');
        if ($username) {
            $this->redirect('index/index');
        }
        return $this->fetch();
    }
    public function index()
    {
        $data = input();
        // 验证规则
        $rule = [
            'username'  => 'require',
            'password' => 'require'
        ];

        $msg = [
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空'
        ];

        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);

        if (true !== $result) {
            return json(['code' => 2, 'msg' => $validate->getError()]);
        }
        //验证验证码是否正确
        if (!captcha_check($data['captcha'])) {
            return json(['code' => 2, 'msg' => '验证码错误']);
        };
        //验证用户名是否存在
        $user =  Db::name('tp_user')->where('username',$data['username'])->find();
        if(!$user){
            return json(['code' => 2, 'msg' => '用户名不存在']);
        }
        if (md5($data['password']) != $user['password']) {
            return json(['code' => 2, 'msg' => '密码错误']);
        }
        $ip = request()->ip();
        Db::name('tp_user')->where('username',$data['username'])
            ->update([
                'last_login_time' =>time(),
                'last_login_ip' =>$ip
            ]);
        // 存储登录凭证 Session
        Session::set('username', $data['username']);
        return json(['code' => 1, 'msg' => '登录成功']);
    }
    // 清除Session
        public function logout () {
            Session::delete('username');
            return $this->redirect('login/login');
    }
}